//
//  UITextField+input.m
//  quinn
//
//  Created by bug neo on 13/12/2020.
//  Copyright © 2020 neobug. All rights reserved.
//

#import "UITextField+inputs.h"

#import <objc/runtime.h>


static const char wj_inputFilterKeyFields;
static const char wj_inputFilterKeyFieldBlocks;
static const char wj_hasAddKeys;
static const char wj_ignoreStrArrayKeys;
static const char wj_maxCountKeys;

@implementation UITextField (inputs)


+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method method1 = class_getInstanceMethod([self class], @selector(field_layoutSubviews));
        Method method2 = class_getInstanceMethod([self class], @selector(layoutSubviews));
        //交换method1和method2的IMP指针，(IMP代表了方法的具体的实现）
        method_exchangeImplementations(method1, method2);
        
        
//        Method method3 = class_getInstanceMethod([NSObject class], @selector(field_awakeFromNib));
//        Method method4 = class_getInstanceMethod([NSObject class], @selector(awakeFromNib));
//        //交换method1和method2的IMP指针，(IMP代表了方法的具体的实现）
//        method_exchangeImplementations(method3, method4);
    });
}


- (void)field_awakeFromNib {
    [self field_awakeFromNib];
    if ([self isKindOfClass:[UITextField class]]) {
        self.wj_inputFilter = YES;
    }
}
- (void)field_layoutSubviews {
    [self field_layoutSubviews];
    self.wj_inputFilter = YES;
}


- (void)setWj_hasAdd:(BOOL)wj_hasAdd {
    objc_setAssociatedObject(self, &wj_hasAddKeys, [NSNumber numberWithBool:wj_hasAdd], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)wj_hasAdd {
    return objc_getAssociatedObject(self, &wj_hasAddKeys);
}

- (void)setWJ_UITextFieldXSSFilterEndBlock:(void (^)(NSString *))WJ_UITextFieldXSSFilterEndBlock {
    objc_setAssociatedObject(self, &wj_inputFilterKeyFieldBlocks, WJ_UITextFieldXSSFilterEndBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(NSString *))WJ_UITextFieldXSSFilterEndBlock {
    return objc_getAssociatedObject(self, &wj_inputFilterKeyFieldBlocks);
}

- (void)setWj_inputFilter:(BOOL)wj_inputFilter {
    objc_setAssociatedObject(self, &wj_inputFilterKeyFields, [NSNumber numberWithBool:wj_inputFilter], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (wj_inputFilter) {
        if (self.wj_hasAdd == NO) {
            [self addTarget];
        }
        self.wj_hasAdd = YES;
    }else {
        self.wj_hasAdd = NO;
        [self removeTarget:self action:@selector(endEdit:) forControlEvents:UIControlEventEditingChanged];
    }
}
- (BOOL)wj_inputFilter {
    return objc_getAssociatedObject(self, &wj_inputFilterKeyFields);
}


- (void)setIgnoreStrArray:(NSArray *)ignoreStrArray {
    objc_setAssociatedObject(self, &wj_ignoreStrArrayKeys, ignoreStrArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSArray *)ignoreStrArray {
    return objc_getAssociatedObject(self, &wj_ignoreStrArrayKeys);
}


- (void)setWj_maxCount:(NSNumber *)wj_maxCount {
    objc_setAssociatedObject(self, &wj_maxCountKeys, wj_maxCount, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSNumber *)wj_maxCount {
    return objc_getAssociatedObject(self, &wj_maxCountKeys);
}

- (void)addTarget {
    [self addTarget:self action:@selector(endEdit:) forControlEvents:UIControlEventEditingChanged];
}

- (void)endEdit:(UITextField *)textField {
    NSArray *arr = @[];
    NSMutableArray *tmp = [arr mutableCopy];
    [self.ignoreStrArray enumerateObjectsUsingBlock:^(NSString  * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([tmp containsObject:obj]) {
            [tmp removeObject:obj];
        }
    }];
    
    arr = [tmp copy];
    
    UITextRange *selectedRange = [textField markedTextRange];
    //获取高亮部分
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行搜索
    if (!position) {
        
        for (int i=0; i<arr.count; i++) {
            if ([textField.text containsString:arr[i]]) {
                textField.text = [textField.text stringByReplacingOccurrencesOfString:arr[i] withString:@""];
            }
            if (self.wj_maxCount && textField.text.length > self.wj_maxCount.integerValue) {
                textField.text = [textField.text substringToIndex:self.wj_maxCount.integerValue];
            }
        }
        
    }
    if (self.WJ_UITextFieldXSSFilterEndBlock) {
        self.WJ_UITextFieldXSSFilterEndBlock(self.text);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kTextFieldXSSFitlerText" object:nil userInfo:@{@"text":self.text?self.text:@""}];
}

@end
